<template>
    <div style="padding: 0 17px">
        <Breadcrumb/>
        <div style="display: flex;margin-top: 20px">
            <el-button icon="edit" type="primary" style="margin-right: 15px" @click="editItem">新增
            </el-button>
            <span style="min-width: 200px;margin-right: 15px">
          <OrganizationTree
                  @change="load"
                  v-model="selectedOrganizationId"
                  @tree-select-changed="treeSelectChanged"
          />
      </span>
            <el-input v-model="search" placeholder="单位名称/地址名称"
                      style="width: 200px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
            <el-button icon="Search" type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;"
                       @click="load">搜索
            </el-button>
            <!--<el-button type="success" style="" @click="importData">导入</el-button>-->
            <!--<el-button type="success" style="" @click="exportData">导出</el-button>-->
        </div>
        <div>
            <el-table :data="tableData" :row-style="{ height: '77px' }" border
                      style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;color: #909399;font-size: 15px;"
                      @selection-change="handleSelectionChange">
                <el-table-column prop="id" label="ID" width="100"/>
                <el-table-column prop="clientName" label="单位名称" width="200"/>
                <el-table-column prop="addrName" label="地址名称" width="auto"/>
                <el-table-column align="center" label="操作" fixed="right" width="180">
                    <template v-slot="scope">
                        <el-button type="primary" size="small" icon="edit" @click="editItem(scope.row)">编辑</el-button>
                        <el-button v-if="this.userInformation.role === 1" type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
                        <el-button type="primary" size="small" @click="qrcodeScan(scope.row.id)">生成二维码</el-button>
                        <el-button type="primary" size="small" @click="downloadQrcode(scope.row)">下载二维码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    :current-page="currentPage"
                    :page-size="pageSize"
                    :page-sizes="[10, 20, 30, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    :background="true"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            />
        </div>
    </div>
    <el-dialog :close-on-click-modal="false" title="地址操作" v-model="operationItemDialog" :show-close="false"
               width="700">
        <el-form :inline="true" :model="form" ref="form" :rules="rules">
            <el-form-item label="单位名称" prop="clientId">
                <el-select style="width: 190px" v-model="form.clientId" filterable placeholder="选择单位名称"
                           autocomplete="off" @change="getAddressOptions(form.clientId)">
                    <el-option
                            v-for="item in clientOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="地址名称" prop="addrName">
                <el-input placeholder="请输入地址名称" v-model="form.addrName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="二维码图片" prop="addrCode" style="width: 100%" class="formItem">
                <el-upload
                        :action="'/api/files/upload'"
                        :on-success="addrCodeHandleSuccess"
                        :on-error="photoHandleError"
                        class="avatar-uploader"
                >
                    <template #tip>
                        <div class="el-upload__tip">
                            {{ photoType() }}文件应小于{{ fileSizeLimit() }}
                        </div>
                    </template>
                    <img width="100" height="100" v-if="form.addrCode" :src="'/api/file/download/' + form.addrCode" class="avatar">
                    <img width="100" height="100" v-else>
                    <template #file="{ file }" style="display:flex;text-align: center;justify-content: center">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="'/api/file/download/' + file.url" alt=""/>
                            <span class="el-upload-list__item-actions">
                  <span
                          class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><zoom-in/></el-icon>
                  </span>
                  <span
                          class="el-upload-list__item-delete"
                          @click="handleRemove(file)"
                  >
                    <el-icon><Delete/></el-icon>
                  </span>
                </span>
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="reset('form')">取 消</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>
    <div v-if="dialogVisible" class="modal" @click="closeModal">
        <div class="modal-content" @click.stop>
            <!-- Close button -->
            <button class="close-btn" @click="closeModal">X</button>
            <img :src="dialogImageUrl" alt="" class="enlarged-image" :style="{ transform: 'scale(' + zoomLevel + ')'}" @wheel="handleZoom">
        </div>
    </div>
    <el-dialog title="导入" v-model="dialogImportVisible" width="520px">
        <el-form label-position="right" label-width="100px">
            <el-form-item label="模板下载:" padding-top:10px>
                <el-button type="primary" size="small" style="" @click="exportTemplate">二维码地址</el-button>
            </el-form-item>
            <el-form-item label="文件" padding-top:-20px>
                <el-upload :headers="headers"
                           :multiple="false"
                           :on-success="onUploadSuccess"
                           :on-error="onUploadError"
                           :action="serverIp+'/inspect-addr-code/importData'"
                           class="upload-demo">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
                </el-upload>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogImportVisible = false">取消</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import request from "@/utils/request.js";
    import Breadcrumb from "@/components/Breadcrumb.vue";
    import OrganizationTree from "@/components/OrganizationTree.vue";
    import {serverIp} from "../../../public/static/config"
    import {Delete, Download, Iphone, Plus, Position, ZoomIn} from "@element-plus/icons-vue";
    import {fileSizeLimit, photoType} from "@/assets/globalJS.js";
    export default {
        name: "InspectAddrCode",
        components: {Breadcrumb, OrganizationTree,Delete, Download, Iphone, Plus, Position, ZoomIn},
        data() {
            return {
                zoomLevel: 1,  // Initial zoom level
                serverIp,
                headers: {
                    token:  JSON.parse(localStorage.getItem('user')).token,
                },
                dialogImportVisible: false,
                operationItemDialog: false,
                userInformation:JSON.parse(localStorage.getItem("user")),
                selectedOrganizationId: JSON.parse(localStorage.getItem("user")).organization,
                tableData: [],
                form:{},
                searchData: [],
                clientOptions:[],
                currentData: {},
                search: "",
                selectOptionName: "",
                currentPage: 1,
                pageSize: 10,
                total: 10,
                // 选择框
                multipleSelection: [],
                rules: {
                    clientId: [
                        {required: true, message: '请选择单位名称', trigger: 'blur'},
                    ],
                    addrName: [
                        {required: true, message: '请输入地址名称', trigger: 'blur'},
                    ],
                },
                informationPhotoList: [],
                dialogImageUrl: "",
                dialogVisible: false,
            }
        },
        created() {
            this.load()
            this.getClientOptions()
        },
        methods: {
            qrcodeScan (id) {
                request.get("/qrCode/generator?content=" + "http://124.167.249.190:9290/addrCode?id=" + id +"&id="+id).then(res => {
                    if (res.code === '200') {
                        this.$message({
                            message: "二维码生成成功",
                            type: "success"
                        })
                        this.load()
                    } else {
                        this.$message.error("二维码生成失败" + res.msg)
                    }
                })
            },
            downloadQrcode (row) {
                window.open(serverIp + '/files/codeDownload/' + row.addrCode.substring(row.addrCode.lastIndexOf("/") + 1));
            },
            importData() {
                this.dialogImportVisible = true;
            },
            onUploadSuccess() {
                this.$message.success('上传成功');
                this.dialogImportVisible = false;
                location.reload();
            },
            onUploadError() {
                this.$message.error('上传失败');
            },
            // 模板下载
            exportTemplate() {
                window.location.href = '../xlsx/inspectAddrCode.xlsx'
            },
            exportData() {
                let level = JSON.parse(localStorage.getItem("user")).level
                let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
                } else {
                    clientIds = [];
                }
                let startTime = "", endTime = ""
                if (this.searchData !== null && this.searchData.length !== 0) {
                    startTime = this.searchData[0]
                    endTime = this.searchData[1]
                }
                window.open(serverIp + '/inspect-addr-code/export?keyWord=' + this.search + "&startTime=" + startTime + "&endTime=" + endTime +
                    "&level=" + level + "&organizationId=" + this.selectedOrganizationId + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds);
            },
            treeSelectChanged(data) {
                this.currentData = data
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log(this.multipleSelection)
            },
            handleSizeChange(pageSize) {   // 改变当前每页的个数触发
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {  // 改变当前页码触发
                this.currentPage = pageNum
                this.load()
            },
            editItem(scope) {
                Object.assign(this.form, scope)
                this.operationItemDialog = true
                this.initinformationPhotoList()
            },
            // 编辑、新增确定按钮
            submitForm(val) {
                this.$refs[val].validate((valid) => {
                    if (valid) {
                        request.post("/inspect-addr-code/edit", this.form).then(res => {
                            if (res.code === '200') {
                                this.$message({
                                    message: "成功",
                                    type: "success"
                                })
                                this.load()
                                this.reset("form")
                            } else {
                                this.$message.error("操作失败" + res.msg)
                            }
                        })
                    }
                })
            },
            reset(val) {
                this.operationItemDialog = false;
                this.form = {};
                this.$refs[val].clearValidate();
            },
            getClientOptions(){
                let level = JSON.parse(localStorage.getItem("user")).level
                let organizationId = JSON.parse(localStorage.getItem("user")).organization
                let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
                } else {
                    clientIds = [];
                }
                request.get("/client/listbyName?name="+this.selectOptionName+"&organizationId="+organizationId+"&level="+level+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res=>{
                    this.clientOptions=res.data
                })
            },
            // 删除单个
            deleteItem(scope){
              this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                request.get("/inspect-addr-code/delete/"+scope).then(res=>{
                  if (res.code==='200'){
                    this.$message.success("成功")
                    this.load()
                  }else {
                    this.$message.error("删除失败，"+res.msg)
                  }
                })
              });
            },
            /*
            deleteSelect(){
              this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                if (this.multipleSelection.length===0){
                  this.$message.error("未选择数据")
                  return
                }
                const idList=[];
                this.multipleSelection.forEach(row => {
                  idList.push(row.id)
                });
                request.post("/record-inspection/deleteByIdList",idList).then(res=>{
                  if (res.code==='200'){
                    if (res.data){
                      this.$message.success("成功")
                    }else {
                      this.$message.error("删除失败")
                    }
                    this.load()
                  }else {
                    this.$message.error("删除失败，"+res.msg)
                  }
                })
              });
            },
             */
            // 搜索及初始化
            load() {
                let level = JSON.parse(localStorage.getItem("user")).level
                if (this.currentData.level !== undefined) {
                    level = this.currentData.level
                }
                let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
                } else {
                    clientIds = [];
                }
                let startTime = "", endTime = ""
                if (this.searchData !== null && this.searchData.length !== 0) {
                    startTime = this.searchData[0]
                    endTime = this.searchData[1]
                }
                request.get("/inspect-addr-code/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&keyWord=" + this.search + "&startTime=" + startTime + "&endTime=" + endTime +
                    "&level=" + level + "&organizationId=" + this.selectedOrganizationId + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
                    if (res.code === '200') {
                        for (let key in res.data) {
                            if (key === "record") {
                                this.tableData = res.data[key];
                            } else if (key === "total") {
                                this.total = res.data[key];
                            }
                        }
                    } else {
                        this.$message.error("错误" + res.msg)
                    }
                })
            },
            photoType() {
                return photoType
            },
            fileSizeLimit() {
                return fileSizeLimit
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = "/api/file/download/"+file.url;
                this.dialogVisible = true;
            },
            addrCodeHandleSuccess(response) {
                this.form.addrCode=`${response}`
            },
            handleRemove(file) {
                this.form.addrCode=''
            },
            photoHandleError() {
                this.$message.error("上传文件大小请勿超过" + fileSizeLimit)
            },
            closeModal() {
                this.dialogImageUrl = ''
                this.dialogVisible = false
                this.zoomLevel = 1; // 重置缩放级别
            },
            handleZoom(event) {
                event.preventDefault(); // 防止页面滚动

                // 根据滚轮方向调整缩放级别
                if (event.deltaY < 0) {
                    this.zoomLevel = Math.min(this.zoomLevel + 0.1, 3); // 最大缩放到3倍
                } else {
                    this.zoomLevel = Math.max(this.zoomLevel - 0.1, 1); // 最小缩放到1倍
                }
            },
        }
    }
</script>

<style scoped>
    .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw; /* 使用视口宽度 */
        height: 100vh; /* 使用视口高度 */
        background-color: rgba(0, 0, 0, 0.9); /* 更深的半透明背景 */
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9000; /* 确保弹窗在最上层 */
    }
    .modal-content {
        position: relative; /* 相对定位，用于定位关闭按钮 */
        width: 100%; /* 弹窗内容宽度为100% */
        height: 100%; /* 弹窗内容高度为100% */
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .close-btn {
        z-index: 9999;
        position: absolute;
        top: 20px; /* 离顶部距离 */
        right: 20px; /* 离右侧距离 */
        background-color: transparent; /* 背景透明 */
        border: none;
        font-size: 24px; /* 字体大小 */
        cursor: pointer;
        color: red; /* 关闭按钮颜色 */
    }

    .close-btn:hover {
        color: red; /* 鼠标悬停时颜色变化 */
    }

    .enlarged-image {
        max-width: 100%; /* 确保图片不会超出弹窗边界 */
        max-height: 100%; /* 确保图片不会超出弹窗边界 */
        border-radius: 0; /* 去掉图片的圆角 */
        transition: transform 0.3s ease; /* 变换过渡效果 */
    }
    :deep(.el-table th .cell) {
        font-weight: 700
    }

    :deep(.el-form-item__label) {
        font-size: 14px;
        font-weight: 700
    }

    .input-size {
        font-size: 14px;
    }
</style>
